//
//  WBUserAccount.swift
//  Weibo
//
//  Created by kobe on 2016/12/25.
//  Copyright © 2016年 kobe. All rights reserved.
//

import UIKit

fileprivate let accountFile:NSString = "userAccount.json"

class WBUserAccount: NSObject {
    
    var access_token:String?
    var uid:String?
    var expires_in:TimeInterval = 0.0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期日期
    var expiresDate:Date?
    
    
    //用户信息
    //昵称
    var screen_name:String?
    //头像
    var avatar_large:String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        
        //从磁盘加载保存的文件
        guard let path = accountFile.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as?[String:Any] else {
                return
        }
        
        
        //使用字典设置属性值
        yy_modelSet(with: dict ?? [:])
        
        //判断token是否过期
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("过期")
            
            //清空信息
            access_token = nil
            uid = nil
            
            //删除
            try? FileManager.default.removeItem(atPath: path)
            
        }
        print("正常")
    }
    
    func saveAccount() {
        
        //模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String:Any]) ?? [:]
        
        //删除expires_in
        dict.removeValue(forKey: "expires_in")
        
        //字典序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filename = accountFile.cz_appendDocumentDir() else {
            return
        }
        
        //写入磁盘
        (data as NSData).write(toFile: filename, atomically: true)
        
        print("用户账户保存成功 \(filename)")
        
        
        
        
    }

}
